package dao.security.impl;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.security.UsrAuth;
import model.security.UsrUser;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.security.core.GrantedAuthority;
import core.dao.impl.BaseDaoImpl;
import dao.security.UsrUserDao;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

@SuppressWarnings("deprecation")
public class UsrUserDAOImpl extends BaseDaoImpl<UsrUser> implements UsrUserDao  {
	public UsrUserDAOImpl(){
		super(UsrUser.class);
	}
	
	public List<GrantedAuthority> getUserAuthByName(String username) {
		try {
			List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			List<String> query1 = loadUserAuth(username);

			for (String roleName : query1) {
				GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
				auths.add(authority);
			}

			return auths;

		} catch (RuntimeException re) {
			//log.error("find by authorities by username failed.", re);
			throw re;
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<String> loadUserAuth(final String username) {
		try {
			return this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public List<UsrAuth> doInHibernate(Session session) throws HibernateException,SQLException {
						String sql="select a.authname "
								+ "from usr_auth a, usr_role_auth ra, usr_user_role ur, usr_user u "
								+ "where   a.authid = ra.authid and ra.roleid = ur.roleid  "
								+ "and ur.userid = u.userid and u.useraccount = '"
								+ username + "'";
						Query query = session.createSQLQuery(sql);
						return query.list();
					}
				});
		} catch (RuntimeException re) {
			//log.error("find by authorities by username failed.", re);
			throw re;
		}
	}
	
	public static UsrUserDao getFromApplicationContext(ApplicationContext ctx) {
    	return (UsrUserDao) ctx.getBean("usrUserDAO");
	}
}